<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户管理 - 列车车次管理系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <link rel="stylesheet" href="/css/admin.css">
</head>
<body>
<div class="container-fluid">
    <div class="row">
        <!-- 侧边栏 -->
        <nav id="sidebar" class="col-md-3 col-lg-2 d-md-block bg-light sidebar collapse">            <div class="position-sticky pt-3">
                <div class="text-center mb-4">
                    <img src="/images/logo.jpeg" alt="Logo" class="sidebar-logo">
                    <h4>列车车次管理系统</h4>
                    <h6 class="text-muted">管理员控制台</h6>
                </div>
                <ul class="nav flex-column">
                    <li class="nav-item">
                        <a class="nav-link" href="/admin/dashboard.html">
                            <i class="bi bi-speedometer2 me-2"></i>
                            仪表盘
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="/admin/users.html">
                            <i class="bi bi-people me-2"></i>
                            用户管理
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/admin/trains.html">
                            <i class="bi bi-train-front me-2"></i>
                            列车管理
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/admin/stations.html">
                            <i class="bi bi-building me-2"></i>
                            车站管理
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/admin/routes.html">
                            <i class="bi bi-map me-2"></i>
                            路线管理
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/admin/schedules.html">
                            <i class="bi bi-calendar-date me-2"></i>
                            时刻表管理
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/admin/tickets.html">
                            <i class="bi bi-ticket-perforated me-2"></i>
                            票务管理
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/">
                            <i class="bi bi-house-door me-2"></i>
                            返回前台
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#" id="logoutBtn">
                            <i class="bi bi-box-arrow-right me-2"></i>
                            退出登录
                        </a>
                    </li>
                </ul>
            </div>
        </nav>

        <!-- 主内容区 -->
        <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
            <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                <h1 class="h2">用户管理</h1>
                <div class="btn-toolbar mb-2 mb-md-0">
                    <div class="btn-group me-2">
                        <button type="button" class="btn btn-sm btn-outline-secondary" id="refreshBtn">
                            <i class="bi bi-arrow-clockwise me-1"></i>刷新
                        </button>
                        <button type="button" class="btn btn-sm btn-outline-secondary" id="exportBtn">
                            <i class="bi bi-download me-1"></i>导出
                        </button>
                    </div>
                    <button type="button" class="btn btn-sm btn-primary" id="addUserBtn">
                        <i class="bi bi-plus-circle me-1"></i>添加用户
                    </button>
                </div>
            </div>

            <!-- 搜索和筛选 -->
            <div class="card mb-4">
                <div class="card-body">
                    <form id="searchForm" class="row g-3">
                        <div class="col-md-3">
                            <label class="form-label">用户名</label>
                            <input type="text" class="form-control" id="searchUsername" placeholder="输入用户名">
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">真实姓名</label>
                            <input type="text" class="form-control" id="searchName" placeholder="输入真实姓名">
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">用户角色</label>
                            <select class="form-select" id="searchRole">
                                <option value="">-- 全部角色 --</option>
                                <option value="USER">普通用户</option>
                                <option value="ADMIN">管理员</option>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">&nbsp;</label>
                            <div class="d-grid">
                                <button type="submit" class="btn btn-primary">
                                    <i class="bi bi-search me-1"></i>搜索
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>

            <!-- 用户列表 -->
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">用户列表</h5>
                </div>
                <div class="card-body">
                    <div id="loadingArea" class="text-center py-5">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">Loading...</span>
                        </div>
                        <p class="mt-2">正在加载用户数据...</p>
                    </div>

                    <div id="usersArea" class="d-none">
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                <tr>
                                    <th>用户ID</th>
                                    <th>用户名</th>
                                    <th>真实姓名</th>
                                    <th>身份证号</th>
                                    <th>手机号</th>
                                    <th>邮箱</th>
                                    <th>角色</th>
                                    <th>注册时间</th>
                                    <th>操作</th>
                                </tr>
                                </thead>
                                <tbody id="usersTable">
                                <!-- 动态加载用户数据 -->
                                </tbody>
                            </table>
                        </div>

                        <!-- 分页 -->
                        <nav aria-label="用户列表分页">
                            <ul class="pagination justify-content-center" id="pagination">
                                <!-- 动态生成分页 -->
                            </ul>
                        </nav>
                    </div>

                    <div id="noUsersArea" class="text-center py-5 d-none">
                        <i class="bi bi-people" style="font-size: 4rem; color: #dee2e6;"></i>
                        <h5 class="text-muted mt-3">暂无用户数据</h5>
                        <p class="text-muted">系统中还没有注册用户</p>
                    </div>
                </div>
            </div>
        </main>
    </div>
</div>

<!-- 添加/编辑用户模态框 -->
<div class="modal fade" id="userModal" tabindex="-1" aria-labelledby="userModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="userModalLabel">添加用户</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="userForm">
                    <input type="hidden" id="userId">
                    
                    <div class="mb-3">
                        <label for="username" class="form-label">用户名 <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="username" required>
                    </div>
                    
                    <div class="mb-3" id="passwordGroup">
                        <label for="password" class="form-label">密码 <span class="text-danger">*</span></label>
                        <input type="password" class="form-control" id="password" required>
                    </div>
                    
                    <div class="mb-3">
                        <label for="name" class="form-label">真实姓名 <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="name" required>
                    </div>
                    
                    <div class="mb-3">
                        <label for="idCard" class="form-label">身份证号 <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="idCard" required>
                    </div>
                    
                    <div class="mb-3">
                        <label for="phone" class="form-label">手机号 <span class="text-danger">*</span></label>
                        <input type="tel" class="form-control" id="phone" required>
                    </div>
                    
                    <div class="mb-3">
                        <label for="email" class="form-label">邮箱</label>
                        <input type="email" class="form-control" id="email">
                    </div>
                    
                    <div class="mb-3">
                        <label for="userRole" class="form-label">用户角色 <span class="text-danger">*</span></label>
                        <select class="form-select" id="userRole" required>
                            <option value="USER">普通用户</option>
                            <option value="ADMIN">管理员</option>
                        </select>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="saveUserBtn">保存</button>
            </div>
        </div>
    </div>
</div>

<!-- 确认删除模态框 -->
<div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="deleteModalLabel">确认删除</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p>您确定要删除用户 <strong id="deleteUserName"></strong> 吗？</p>
                <p class="text-danger">此操作不可撤销！</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" id="confirmDeleteBtn">确认删除</button>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="/js/admin.js"></script>
<script>
    let allUsers = [];
    let filteredUsers = [];
    let currentPage = 1;
    let usersPerPage = 10;
    let currentEditingUserId = null;

    $(document).ready(function() {
        // 检查管理员权限
        checkAdminPermission();
        
        // 加载用户数据
        loadUsers();

        // 搜索表单提交
        $('#searchForm').on('submit', function(e) {
            e.preventDefault();
            filterUsers();
        });

        // 刷新按钮
        $('#refreshBtn').on('click', function() {
            loadUsers();
        });

        // 添加用户按钮
        $('#addUserBtn').on('click', function() {
            openUserModal();
        });

        // 保存用户
        $('#saveUserBtn').on('click', function() {
            saveUser();
        });

        // 确认删除
        $('#confirmDeleteBtn').on('click', function() {
            if (currentEditingUserId) {
                deleteUser(currentEditingUserId);
            }
        });

        // 退出登录
        $('#logoutBtn').on('click', function(e) {
            e.preventDefault();
            $.ajax({
                url: '/logout',
                type: 'POST',
                success: function() {
                    window.location.href = '/custom-login';
                }
            });
        });

        // 导出按钮
        $('#exportBtn').on('click', function() {
            exportUsers();
        });
    });

    // 检查管理员权限
    function checkAdminPermission() {
        $.ajax({
            url: '/api/users/current',
            type: 'GET',
            success: function(user) {
                if (user.userRole !== 'ADMIN') {
                    alert('您没有访问管理后台的权限');
                    window.location.href = '/';
                }
            },
            error: function() {
                alert('请先登录');
                window.location.href = '/custom-login?redirect=' + encodeURIComponent(window.location.href);
            }
        });
    }

    // 加载用户数据
    function loadUsers() {
        $('#loadingArea').removeClass('d-none');
        $('#usersArea').addClass('d-none');
        $('#noUsersArea').addClass('d-none');

        $.ajax({
            url: '/api/users',
            type: 'GET',
            success: function(users) {
                allUsers = users;
                filteredUsers = users;
                
                $('#loadingArea').addClass('d-none');
                
                if (users.length === 0) {
                    $('#noUsersArea').removeClass('d-none');
                } else {
                    renderUsersTable();
                    $('#usersArea').removeClass('d-none');
                }
            },
            error: function(xhr) {
                $('#loadingArea').addClass('d-none');
                alert('加载用户数据失败: ' + (xhr.responseText || '请稍后重试'));
            }
        });
    }

    // 筛选用户
    function filterUsers() {
        const username = $('#searchUsername').val().toLowerCase();
        const name = $('#searchName').val().toLowerCase();
        const role = $('#searchRole').val();

        filteredUsers = allUsers.filter(user => {
            return (!username || user.username.toLowerCase().includes(username)) &&
                   (!name || user.name.toLowerCase().includes(name)) &&
                   (!role || user.userRole === role);
        });

        currentPage = 1;
        renderUsersTable();
    }

    // 渲染用户表格
    function renderUsersTable() {
        const startIndex = (currentPage - 1) * usersPerPage;
        const endIndex = startIndex + usersPerPage;
        const pageUsers = filteredUsers.slice(startIndex, endIndex);

        let tableHtml = '';
        pageUsers.forEach(user => {
            tableHtml += `
                <tr>
                    <td>${user.id}</td>
                    <td>${user.username}</td>
                    <td>${user.name || 'N/A'}</td>
                    <td>${user.idCard ? maskIdCard(user.idCard) : 'N/A'}</td>
                    <td>${user.phone || 'N/A'}</td>
                    <td>${user.email || 'N/A'}</td>
                    <td>${getRoleBadge(user.userRole)}</td>
                    <td>${formatDate(user.createTime)}</td>
                    <td>
                        <button class="btn btn-outline-primary btn-sm me-1" onclick="editUser(${user.id})" title="编辑">
                            <i class="bi bi-pencil"></i>
                        </button>
                        <button class="btn btn-outline-danger btn-sm" onclick="showDeleteModal(${user.id}, '${user.username}')" title="删除">
                            <i class="bi bi-trash"></i>
                        </button>
                    </td>
                </tr>
            `;
        });

        $('#usersTable').html(tableHtml);
        renderPagination();
    }

    // 渲染分页
    function renderPagination() {
        const totalPages = Math.ceil(filteredUsers.length / usersPerPage);
        let paginationHtml = '';

        // 上一页
        if (currentPage > 1) {
            paginationHtml += `<li class="page-item"><a class="page-link" href="#" onclick="changePage(${currentPage - 1})">上一页</a></li>`;
        }

        // 页码
        for (let i = 1; i <= totalPages; i++) {
            if (i === currentPage) {
                paginationHtml += `<li class="page-item active"><a class="page-link" href="#">${i}</a></li>`;
            } else if (Math.abs(i - currentPage) <= 2 || i === 1 || i === totalPages) {
                paginationHtml += `<li class="page-item"><a class="page-link" href="#" onclick="changePage(${i})">${i}</a></li>`;
            } else if (Math.abs(i - currentPage) === 3) {
                paginationHtml += `<li class="page-item disabled"><a class="page-link" href="#">...</a></li>`;
            }
        }

        // 下一页
        if (currentPage < totalPages) {
            paginationHtml += `<li class="page-item"><a class="page-link" href="#" onclick="changePage(${currentPage + 1})">下一页</a></li>`;
        }

        $('#pagination').html(paginationHtml);
    }

    // 切换页面
    function changePage(page) {
        currentPage = page;
        renderUsersTable();
    }

    // 打开用户模态框
    function openUserModal(user = null) {
        currentEditingUserId = user ? user.id : null;
        
        if (user) {
            $('#userModalLabel').text('编辑用户');
            $('#userId').val(user.id);
            $('#username').val(user.username);
            $('#name').val(user.name);
            $('#idCard').val(user.idCard);
            $('#phone').val(user.phone);
            $('#email').val(user.email);
            $('#userRole').val(user.userRole);
            
            // 编辑时密码不是必填的
            $('#password').removeAttr('required');
            $('#passwordGroup label').html('密码 <span class="text-muted">(留空表示不修改)</span>');
        } else {
            $('#userModalLabel').text('添加用户');
            $('#userForm')[0].reset();
            $('#password').attr('required', 'required');
            $('#passwordGroup label').html('密码 <span class="text-danger">*</span>');
        }
        
        $('#userModal').modal('show');
    }

    // 编辑用户
    function editUser(userId) {
        const user = allUsers.find(u => u.id === userId);
        if (user) {
            openUserModal(user);
        }
    }

    // 保存用户
    function saveUser() {
        if (!$('#userForm')[0].checkValidity()) {
            $('#userForm').addClass('was-validated');
            return;
        }

        const userData = {
            username: $('#username').val(),
            name: $('#name').val(),
            idCard: $('#idCard').val(),
            phone: $('#phone').val(),
            email: $('#email').val(),
            userRole: $('#userRole').val()
        };

        // 如果密码有值，则包含密码
        if ($('#password').val()) {
            userData.password = $('#password').val();
        }

        const url = currentEditingUserId ? `/api/users/${currentEditingUserId}` : '/api/users';
        const method = currentEditingUserId ? 'PUT' : 'POST';

        $.ajax({
            url: url,
            type: method,
            contentType: 'application/json',
            data: JSON.stringify(userData),
            success: function() {
                $('#userModal').modal('hide');
                alert(currentEditingUserId ? '用户更新成功' : '用户添加成功');
                loadUsers();
            },
            error: function(xhr) {
                alert('保存失败: ' + (xhr.responseText || '请稍后重试'));
            }
        });
    }

    // 显示删除确认模态框
    function showDeleteModal(userId, username) {
        currentEditingUserId = userId;
        $('#deleteUserName').text(username);
        $('#deleteModal').modal('show');
    }

    // 删除用户
    function deleteUser(userId) {
        $.ajax({
            url: `/api/users/${userId}`,
            type: 'DELETE',
            success: function() {
                $('#deleteModal').modal('hide');
                alert('用户删除成功');
                loadUsers();
            },
            error: function(xhr) {
                alert('删除失败: ' + (xhr.responseText || '请稍后重试'));
            }
        });
    }

    // 导出用户数据
    function exportUsers() {
        const csvContent = generateCSV(filteredUsers);
        downloadCSV(csvContent, 'users.csv');
    }

    // 生成CSV内容
    function generateCSV(users) {
        const headers = ['用户ID', '用户名', '真实姓名', '身份证号', '手机号', '邮箱', '角色', '注册时间'];
        let csvContent = headers.join(',') + '\n';
        
        users.forEach(user => {
            const row = [
                user.id,
                user.username,
                user.name || '',
                user.idCard || '',
                user.phone || '',
                user.email || '',
                user.userRole,
                formatDate(user.createTime)
            ];
            csvContent += row.join(',') + '\n';
        });
        
        return csvContent;
    }

    // 下载CSV文件
    function downloadCSV(content, filename) {
        const blob = new Blob([content], { type: 'text/csv;charset=utf-8;' });
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = filename;
        link.click();
    }

    // 工具函数
    function maskIdCard(idCard) {
        if (!idCard || idCard.length < 8) return idCard;
        return idCard.substring(0, 4) + '****' + idCard.substring(idCard.length - 4);
    }

    function getRoleBadge(role) {
        return role === 'ADMIN' ? 
            '<span class="badge bg-danger">管理员</span>' : 
            '<span class="badge bg-primary">普通用户</span>';
    }

    function formatDate(dateString) {
        if (!dateString) return 'N/A';
        const date = new Date(dateString);
        return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN');
    }
</script>
</body>
</html>
